#include "oj_server.hpp"
#include <iostream>
#include <jsoncpp/json/json.h>
#include <curl/curl.h>

const std::string oj_root_path = "../oj_server/wwwRoot"; // 用于读入写入前置
const std::string avatar_path_io_dir = "../oj_server/wwwRoot/resource/avatar/"; // 用于读入写入
const std::string avatar_path_web = "/resource/avatar/"; // 用于访问

ServerWrapper *serverInstance = nullptr;

ServerWrapper::ServerWrapper() 
    : user(DATABASE__HOST, USER_TABLE_USER, USER_TABLE_PASSWD, DATABASE), 
      ctrl_ptr(new Controller()), _article(nullptr), _video(nullptr), _comment(nullptr), _post(nullptr)
      // _threadPool(std::make_shared<comm::ThreadPool>(5)) 
{
    server = std::make_shared<httplib::Server>();
    serverInstance = this;
    _article = std::make_shared<ArticleManager>(DATABASE__HOST, USER_TABLE_USER, USER_TABLE_PASSWD, DATABASE);
    _video = std::make_shared<VideoManager>(DATABASE__HOST, USER_TABLE_USER, USER_TABLE_PASSWD, DATABASE);
    _comment = std::make_shared<CommentManager>(DATABASE__HOST, USER_TABLE_USER, USER_TABLE_PASSWD, DATABASE);
    _post = std::make_shared<PostManager>(DATABASE__HOST, USER_TABLE_USER, USER_TABLE_PASSWD, DATABASE);

    // 设置默认路径
    server->set_base_dir("./wwwRoot");
}

// template <typename Handler>
// void asyncHandler(const httplib::Request &req, httplib::Response &resp, Handler handler) {
//     _threadPool->enqueue([this, req, &resp, handler]() mutable {
//         try {
//             handler(req, resp);
//         } catch (const std::exception &e) {
//             resp.status = 500; // 内部服务器错误
//             resp.set_content(std::string("Server error: ") + e.what(), "text/plain");
//         }
//     });
// }

void ServerWrapper::Recovery(int sig) {
    if (serverInstance->ctrl_ptr) {
        serverInstance->ctrl_ptr->RecoveryMachines();
    }
}

void ServerWrapper::initRoutes() {
    server->Post("/submit_application.html", [&](const httplib::Request &req, httplib::Response &resp) {
        handleSubmitApplication(req, resp);
    });

    server->Post("/api/login", [&](const httplib::Request &req, httplib::Response &resp) {
        handleLogin(req, resp);
    });

    server->Post("/api/register", [&](const httplib::Request &req, httplib::Response &resp) {
        handleRegister(req, resp);
    });

    server->Get("/api/logout", [&](const httplib::Request &req, httplib::Response &resp) {
        handleLogout(req, resp);
    });

    server->Post("/api/log-off", [&](const httplib::Request &req, httplib::Response &resp) {
        handleLogOff(req, resp);
    });

    server->Post("/api/update-user-info", [&](const httplib::Request &req, httplib::Response &resp) {
        handleUpdateUserInfo(req, resp);
    });

    server->Get("/api/user-info", [&](const httplib::Request &req, httplib::Response &resp) {
        handleUserInfo(req, resp);
    });

    server->Get("/all_questions.html", [&](const httplib::Request &req, httplib::Response &resp) {
        handleAllQuestions(req, resp);
    });

    server->Get(R"(/question/(\d+))", [&](const httplib::Request &req, httplib::Response &resp) {
        handleSingleQuestion(req, resp);
    });

    server->Post(R"(/judge/(\d+))", [&](const httplib::Request &req, httplib::Response &resp) {
        handleJudge(req, resp);
    });

    server->Post(R"(/api/ai-chat)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleAIChat(req, resp);
    });

    server->Get(R"(/api/get-articles)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleGetArticles(req, resp);
    });

    server->Get(R"(/api/get-article)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleGetArticleById(req, resp);
    });

    server->Get(R"(/api/get-videos)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleGetVideos(req, resp);
    });

    server->Get(R"(/api/check-login-status)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleCheckLoginStatus(req, resp);
    });

    server->Post(R"(/api/add-comment)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleAddComment(req, resp);
    });

    server->Post(R"(/api/like-article)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleLikeArticle(req, resp);
    });

    server->Post(R"(/api/increase-view-count)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleIncreaseViewCount(req, resp);
    });

    server->Get(R"(/api/get-comments)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleGetComments(req, resp);
    });

    server->Post(R"(/submit_article)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleAddArticle(req, resp);
    });
    
    server->Get(R"(/api/get-posts)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleGetPosts(req, resp);
    });

    server->Post(R"(/api/add-post)", [&](const httplib::Request &req, httplib::Response &resp) {
        handleAddPost(req, resp);
    });
}

// void ServerWrapper::initRoutes() {
//     server->Post("/submit_application.html", [&](const httplib::Request &req, httplib::Response &resp) {
//         _threadPool->enqueue([this, req = req, resp = resp]() mutable {
//             handleSubmitApplication(req, resp);
//         });
//     });
// }

void ServerWrapper::start(int port) {
    // signal(SIGQUIT, Recovery);
    initRoutes();
    std::cout << "Server listening on port " << port << std::endl;

    // 启动一个线程监听用户输入
    std::thread inputThread(&ServerWrapper::listenForQuitCommand, this);

    // 启动服务器
    server->listen("0.0.0.0", port);

    // 等待输入线程结束
    inputThread.join();
}

void ServerWrapper::stop() {
    server->stop();
}

void ServerWrapper::listenForQuitCommand() {
    std::string input;
    while (running) {
        std::getline(std::cin, input);
        if (input == "quit" || input == "q") {
            std::cout << "Server is stopping..." << std::endl;
            stop();
            break;
        }
    }
}

inline int ServerWrapper::getUserId(const httplib::Request &req)
{
    std::string cookies = req.get_header_value("Cookie");
    LOG_DEBUG() << "Cookies: " << cookies;  // 打印 Cookie
    std::string session_id = StringUtil::extract_session_id(cookies);
    LOG_DEBUG() << "Session ID: " << session_id;  // 打印 Session ID
    if (session_id.empty() || session_store.find(session_id) == session_store.end())
    {
        LOG_ERROR() << "Invalid session ID or session not found.";
        // return -1;
    }

    std::string username = session_store[session_id];
    LOG_DEBUG() << "Username: " << username;  // 打印用户名
    int user_id = user.getUserId(username);
    if (user_id < 0)
    {
        LOG_ERROR() << "Failed to retrieve user ID for username: " << username;
    }
    return user_id;
}

void ServerWrapper::handleLogin(const httplib::Request &req, httplib::Response &resp) {
    resp.set_header("Content-Type", "application/json");

    // 检查请求参数
    if (!req.has_param("username") || !req.has_param("password") || !req.has_param("email")) {
        Json::Value errorJson;
        errorJson["status"] = "error";
        errorJson["message"] = "登录失败: 参数缺失";
        resp.status = 400;
        resp.set_content(errorJson.toStyledString(), "application/json");
        return;
    }

    std::string username = req.get_param_value("username");
    std::string password = req.get_param_value("password");
    std::string email = req.get_param_value("email");

    // 哈希密码
    std::string hashedPassword = StringUtil::hashPassword(password);

    Json::Value responseJson;

    // 验证用户信息
    if (user.login(username, hashedPassword, email)) {
        responseJson["status"] = "success";
        responseJson["message"] = "登录成功";

        std::string session_id = StringUtil::generate_session_id();
        LOG_DEBUG() << "Generated session ID: " << session_id;
        session_store[session_id] = username;

        // 设置 Cookie，30 天有效
        resp.set_header("Set-Cookie", "session_id=" + session_id + "; Path=/");
        resp.status = 200;
    } else {
        responseJson["status"] = "error";
        responseJson["message"] = "登录失败: 用户名或密码错误";
        resp.status = 401;
    }

    // 返回 JSON 响应
    resp.set_content(responseJson.toStyledString(), "application/json");
}


void ServerWrapper::handleRegister(const httplib::Request &req, httplib::Response &resp) {
    std::string username = req.get_param_value("username");
    std::string email = req.get_param_value("email");
    std::string password = req.get_param_value("password");

    // 哈希密码
    std::string hashedPassword = StringUtil::hashPassword(password);

    Json::Value jsonResponse;
    std::string message;
    bool success = user.registerUser(username, hashedPassword, email, message);
    jsonResponse["status"] = success ? "success" : "error";
    jsonResponse["message"] = message;

    Json::StreamWriterBuilder writer;
    std::string jsonString = Json::writeString(writer, jsonResponse);
    resp.set_content(jsonString, "application/json; charset=utf-8");
    resp.status = success ? 200 : 400;
}

// void ServerWrapper::handleLogin(const httplib::Request &req, httplib::Response &resp) {
//     resp.set_header("Content-Type", "application/json");

//     // 检查请求参数
//     if (!req.has_param("username") || !req.has_param("password") || !req.has_param("email")) {
//         Json::Value errorJson;
//         errorJson["status"] = "error";
//         errorJson["message"] = "登录失败: 参数缺失";
//         resp.status = 400;
//         resp.set_content(errorJson.toStyledString(), "application/json");
//         return;
//     }

//     std::string username = req.get_param_value("username");
//     std::string password = req.get_param_value("password");
//     std::string email = req.get_param_value("email");
//     Json::Value responseJson;

//     // 验证用户信息
//     if (user.login(username, password, email)) {
//         responseJson["status"] = "success";
//         responseJson["message"] = "登录成功";

//         std::string session_id = StringUtil::generate_session_id();
//         LOG_DEBUG() << "Generated session ID: " << session_id;
//         session_store[session_id] = username;

//         // 设置 Cookie，30 天有效
//         // resp.set_header("Set-Cookie", "session_id=" + session_id + "; Path=/; Max-Age=2592000");
//         resp.set_header("Set-Cookie", "session_id=" + session_id + "; Path=/");

//         resp.status = 200;
//     } else {
//         responseJson["status"] = "error";
//         responseJson["message"] = "登录失败: 用户名或密码错误";
//         resp.status = 401;
//     }

//     // 返回 JSON 响应
//     resp.set_content(responseJson.toStyledString(), "application/json");
// }

// void ServerWrapper::handleRegister(const httplib::Request &req, httplib::Response &resp) {
//     std::string username = req.get_param_value("username");
//     std::string email = req.get_param_value("email");
//     std::string password = req.get_param_value("password");
//     Json::Value jsonResponse;

//     std::string message;
//     bool success = user.registerUser(username, password, email, message);
//     jsonResponse["status"] = success ? "success" : "error";
//     jsonResponse["message"] = message;

//     Json::StreamWriterBuilder writer;
//     std::string jsonString = Json::writeString(writer, jsonResponse);
//     resp.set_content(jsonString, "application/json; charset=utf-8");
//     resp.status = success ? 200 : 400;
// }

void ServerWrapper::handleLogout(const httplib::Request &req, httplib::Response &resp) {
    auto cookies = req.get_header_value("Cookie");
    std::string session_id = StringUtil::extract_session_id(cookies);

    session_store.erase(session_id);
    resp.set_header("Set-Cookie", "session_id=; expires=Thu, 01 Jan 1970 00:00:00 GMT");
    resp.status = 302;
    resp.set_header("Location", "/login.html");
}

void ServerWrapper::handleLogOff(const httplib::Request &req, httplib::Response &resp) {
    auto cookies = req.get_header_value("Cookie");
    std::string session_id = StringUtil::extract_session_id(cookies);
    std::string username = session_store[session_id];

    if (!username.empty() && user.logoff(username)) {
        session_store.erase(session_id);
        resp.set_header("Set-Cookie", "session_id=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/");
        resp.status = 302;
        resp.set_header("Location", "/login.html");
    } else {
        resp.status = 500;
        resp.set_content("Logout failed", "text/plain");
    }
}

void ServerWrapper::handleUpdateUserInfo(const httplib::Request &req, httplib::Response &resp) {
    LOG(DEBUG) << "recive UpdateUserInfo request" << std::endl;
    auto cookies = req.get_header_value("Cookie");
    std::string session_id = StringUtil::extract_session_id(cookies);
    std::string username = session_store[session_id];

    // 初始化 JSON 对象来存储新用户信息
    Json::Value newInfo;
    std::string fields[] = {"username", "email", "phone", "gender", "description"};

    // 检查并获取每个字段的值
    for (const std::string &field : fields) {
        if (req.has_file(field.c_str())) {  // 非文件字段应使用 has_param
            newInfo[field] = req.get_file_value(field.c_str()).content;
        } else {
            resp.status = 400;
            resp.set_content("{\"status\":\"error\",\"message\":\"Missing field: " + field + "\"}", "application/json");
            LOG(ERROR) << "Missing field: " << field << std::endl;
            return;
        }
    }

    // 处理 avatar 文件
    if (req.has_file("avatar")) {
        httplib::MultipartFormData avatar = req.get_file_value("avatar");
        std::string avatar_filename = username + '-' + avatar.filename;
        std::string avatar_path_io = avatar_path_io_dir + avatar_filename;

        LOG(DEBUG) << "avatar_filename : " << avatar_filename << std::endl;
        if (!FileUtil::SetContent(avatar_path_io, avatar.content)) {  // 写入文件
            resp.status = 500;
            resp.set_content("{\"status\":\"error\",\"message\":\"Avatar upload failed\"}", "application/json");
            LOG(ERROR) << "Avatar upload failed" << std::endl;
            return;
        }

        newInfo["avatar"] = avatar_path_web + avatar_filename;  // 设置相对路径
        LOG(DEBUG) << "avatarfile: " << newInfo["avatar"].asString() << std::endl;
    }

    // 删除旧文件
    std::string oldAvatar = oj_root_path + user.getUserInfo(username)["avatarUrl"].asString();
    // LOG(DEBUG) << "oldAvatar: " << oldAvatar << std::endl;
    if (!oldAvatar.empty() && FileUtil::RemoveFile(oldAvatar)) {
        LOG(DEBUG) << "old avatar file removed: " << oldAvatar << endl;
    } else {
        LOG(ERROR) << "old avatar file not found or remove failed: " << oldAvatar << endl;
    }
    // LOG(DEBUG) << "newInfo: " << newInfo.toStyledString() << std::endl;

    // 调用用户信息更新逻辑
    std::string response;
    if (user.updateUserInfo(username, newInfo, response)) {
        resp.set_content("{\"status\":\"success\",\"message\":\"User info updated successfully\", \"userInfo\":" + Json::writeString(Json::StreamWriterBuilder(), newInfo) + "}", "application/json");
    } else {
        resp.status = 500;
        resp.set_content("{\"status\":\"error\",\"message\":\"" + response + "\"}", "application/json");
        LOG(ERROR) << "User info update failed: " << response << std::endl;
    }
}

void ServerWrapper::handleUserInfo(const httplib::Request &req, httplib::Response &resp) {
    auto cookies = req.get_header_value("Cookie");
    std::string session_id = StringUtil::extract_session_id(cookies);
    Json::Value responseJson;
    // LOG(DEBUG) << "session_id: " << session_id << std::endl;

    if (!session_id.empty() && session_store.find(session_id) != session_store.end()) {
        std::string username = session_store[session_id];
        Json::Value userInfo = user.getUserInfo(username);
        if (!userInfo.isNull()) {
            responseJson["status"] = "success";
            responseJson["message"] = "用户信息获取成功";
            responseJson["data"] = userInfo;
        } else {
            LOG(ERROR) << "User info not found" << std::endl;
            responseJson["status"] = "error";
            responseJson["message"] = "无法获取用户信息";
        }
    } else {
        LOG(ERROR) << "User not logged in" << std::endl;
        responseJson["status"] = "error";
        responseJson["message"] = "用户未登录";
    }

    Json::StreamWriterBuilder writer;
    std::string responseBody = Json::writeString(writer, responseJson);
    resp.set_content(responseBody, "application/json; charset=utf-8");
}

void ServerWrapper::handleSubmitApplication(const httplib::Request &req, httplib::Response &resp) {
    resp.status = 302;
    resp.set_header("Location", "/submit_application.html");
}

void ServerWrapper::handleAllQuestions(const httplib::Request &req, httplib::Response &resp) {
    std::string html;
    ctrl_ptr->AllQuestionToHtml(&html);
    resp.set_content(html, "text/html; charset=utf-8");
}

void ServerWrapper::handleSingleQuestion(const httplib::Request &req, httplib::Response &resp) {
    std::string number = req.matches[1];
    std::string html;
    ctrl_ptr->SingleQuestionToHtml(number, &html);
    resp.set_content(html, "text/html; charset=utf-8");
}

void ServerWrapper::handleJudge(const httplib::Request &req, httplib::Response &resp) {
    std::string number = req.matches[1];
    std::string result_json;
    ctrl_ptr->Judge(number, req.body, &result_json);
    resp.set_content(result_json, "application/json; charset=utf8");
}

// 用于处理 libcurl 响应数据的回调函数
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t total_size = size * nmemb;
    std::string *response_data = reinterpret_cast<std::string*>(userp);
    response_data->append(reinterpret_cast<char*>(contents), total_size);
    return total_size;
}

void ServerWrapper::handleAIChat(const httplib::Request &req, httplib::Response &resp) {
    // 从请求中获取用户的输入（假设请求体是 JSON 格式）
    Json::Value user_message_json;
    Json::Reader reader;
    if (!reader.parse(req.body, user_message_json)) {
        resp.status = 400; // Bad Request
        resp.set_content("Invalid JSON in request body", "text/plain");
        return;
    }

    if (!user_message_json.isMember("message") || user_message_json["message"].asString().empty()) {
        resp.status = 400; // Bad Request
        resp.set_content("Missing 'message' field in JSON", "text/plain");
        return;
    }
    
    std::string user_message = user_message_json["message"].asString();

    // 初始化 libcurl
    CURL *curl = curl_easy_init();
    if (curl) {
        // 设置请求方式为 POST
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.mindcraft.com.cn/v1/chat/completions");

        // 允许重定向
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

        // 默认使用 https 协议
        curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");

        // 设置请求头
        struct curl_slist *headers = NULL;
        std::string api_key = FileUtil::read_api_key("../comm/resource/ai-chat-apikey.txt"); // 从文件读取 API 密钥
        headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key).c_str());
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 构建请求体数据（动态插入用户消息）
        Json::Value root;
        root["model"] = "GLM-4-Flash";
        root["temperature"] = 0.2;
        root["max_tokens"] = 2000;
        root["stream"] = false;
        root["web_search"] = false;

        Json::Value messages(Json::arrayValue);
        Json::Value system_message;
        system_message["role"] = "system";
        system_message["content"] = "你是智酱，用于帮助用户解决遇到的各种计算机编程问题。";
        messages.append(system_message);

        Json::Value user_message_json_value;
        user_message_json_value["role"] = "user";
        user_message_json_value["content"] = user_message;
        messages.append(user_message_json_value);

        root["messages"] = messages;

        Json::StreamWriterBuilder writer;
        std::string data = Json::writeString(writer, root);

        // 设置 POST 数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());

        // 用于接收响应数据
        std::string response_data;

        // 设置响应数据回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_data);

        // 执行请求
        CURLcode res = curl_easy_perform(curl);

        // 错误处理
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            resp.status = 500; // Internal Server Error
            resp.set_content("Error in communicating with AI service", "text/plain");
        } else {
            // 设置响应状态为 200 OK，返回 AI 的响应
            resp.status = 200;
            resp.set_content(response_data, "application/json");
        }

        // 清理资源
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    } else {
        resp.status = 500; // Internal Server Error
        resp.set_content("Failed to initialize cURL", "text/plain");
    }
}

void ServerWrapper::handleGetArticles(const httplib::Request &req, httplib::Response &resp)
{
    // LOG_DEBUG() << "handleGetArticles " << req.method << " " << req.path;
    std::vector<Article> articles;
    Json::Value responseJson;

    if (!_article->GetAllArticles(articles))
    {
        LOG_ERROR() << "无法获取文章数据";
        responseJson["status"] = "error";
        responseJson["message"] = "无法获取文章数据";
        resp.status = 500;
    }
    else
    {
        responseJson["status"] = "success";
        Json::Value articlesJson;

        for (const auto &article : articles)
        {
            Json::Value articleJson;
            articleJson["article_id"] = article.article_id;
            articleJson["title"] = article.title;
            articleJson["author"] = user.getNameById(article.author_id);
            articleJson["publish_date"] = article.publish_date;
            articleJson["summary"] = article.summary;
            articleJson["content"] = article.content;
            articleJson["category"] = article.category;
            articleJson["image_url"] = article.image_url;
            articleJson["view_count"] = article.view_count;
            articleJson["like_count"] = article.like_count;
            articleJson["comment_count"] = article.comment_count;
            articleJson["share_count"] = article.share_count;

            Json::Value tagsJson;
            for (const auto &tag : article.tags)
            {
                tagsJson.append(tag);
            }
            articleJson["tags"] = tagsJson;

            articlesJson.append(articleJson);
        }

        responseJson["articles"] = articlesJson;
        resp.status = 200;
    }

    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleGetArticleById(const httplib::Request &req, httplib::Response &resp)
{
    LOG_DEBUG() << "handleGetArticleById " << req.method << " " << req.path;

    std::string tmp = req.get_param_value("id");
    int articleId = std::stoi(tmp);
    LOG_DEBUG() << "article_id: " << articleId;
    Article article;

    Json::Value responseJson;
    if (!_article->GetArticleById(articleId, article))
    {
        LOG_ERROR() << "无法获取指定文章数据";
        responseJson["status"] = "error";
        responseJson["message"] = "无法获取指定文章数据";
        resp.status = 500;
    }
    else
    {
        responseJson["status"] = "success";

        Json::Value articleJson;
        articleJson["article_id"] = article.article_id;
        articleJson["title"] = article.title;
        // articleJson["author_id"] = article.author_id;
        articleJson["author"] = user.getNameById(article.author_id);
        articleJson["publish_date"] = article.publish_date;
        articleJson["summary"] = article.summary;
        articleJson["content"] = article.content;
        articleJson["category"] = article.category;
        articleJson["image_url"] = article.image_url;
        articleJson["view_count"] = article.view_count;
        articleJson["like_count"] = article.like_count;
        articleJson["comment_count"] = article.comment_count;
        articleJson["share_count"] = article.share_count;

        Json::Value tagsJson;
        for (const auto &tag : article.tags)
        {
            tagsJson.append(tag);
        }
        articleJson["tags"] = tagsJson;

        responseJson["article"] = articleJson;
        resp.status = 200;
    }

    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleAddArticle(const httplib::Request &req, httplib::Response &resp)
{
    LOG_DEBUG() << "handleAddArticle " << req.method << " " << req.path;

    // 检查请求是否为 multipart/form-data
    if (!req.is_multipart_form_data())
    {
        LOG_ERROR() << "Request is not multipart/form-data.";
        resp.status = 400;
        resp.set_content("{\"status\":\"error\", \"message\":\"请求格式不正确\"}", "application/json");
        return;
    }

    // 初始化 Article 对象
    Article article;
    
    article.author_id = getUserId(req); // 从会话中获取用户 ID
    if (article.author_id <= 0)
    {
        LOG_ERROR() << "Invalid author_id: " << article.author_id;
        resp.status = 401;
        resp.set_content("{\"status\":\"error\",\"message\":\"用户未登录或会话无效\"}", "application/json");
        return;
    }
    LOG_DEBUG() << "author_id: " << article.author_id;

    // 解析表单数据
    for (const auto &file : req.files)
    {
        const auto &name = file.first;
        const auto &value = file.second;

        if (name == "title")
        {
            article.title = value.content;
        }
        else if (name == "summary")
        {
            article.summary = value.content;
        }
        else if (name == "category")
        {
            article.category = value.content;
        }
        else if (name == "content")
        {
            article.content = value.content;
        }
        else if (name == "tags")
        {
            std::istringstream ss(value.content);
            std::string tag;
            while (std::getline(ss, tag, ','))
            {
                article.tags.push_back(tag);
            }
        }
        else if (name == "image_url")
        {
            const std::string thumb_web_path = "/resource/thumbnail/";
            const std::string thumb_storage_path = "../oj_server/wwwRoot/resource/thumbnail/";

            std::string image_path = thumb_storage_path + value.filename;
            if (!FileUtil::SetContent(image_path, value.content))
            {
                LOG_ERROR() << "Failed to save image file: " << value.filename;
                resp.status = 500;
                resp.set_content("{\"status\":\"error\",\"message\":\"上传图片失败\"}", "application/json");
                return;
            }

            article.image_url = thumb_web_path + value.filename;
        }
    }

    // 默认值设置
    article.publish_date = TimeUtil::GetDateTime();
    article.view_count = 0;
    article.like_count = 0;
    article.comment_count = 0;
    article.share_count = 0;

    // 尝试添加文章
    Json::Value responseJson;
    if (!_article->AddArticle(article))
    {
        LOG_ERROR() << "Failed to add article: " << article.title;
        responseJson["status"] = "error";
        responseJson["message"] = "添加文章失败";
        resp.status = 500;
    }
    else
    {
        LOG_INFO() << "Article successfully added: " << article.title;
        responseJson["status"] = "success";
        responseJson["message"] = "文章已成功添加";
        resp.status = 200;
    }

    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleGetVideos(const httplib::Request &req, httplib::Response &resp)
{
    // LOG_DEBUG() << " handleGetVideos " << req.method << " " << req.path;

    if (req.method != "GET")
    {
        resp.status = 405;
        resp.set_content(R"({"status":"error","message":"Method Not Allowed"})", "application/json");
        return;
    }

    std::vector<Video> videoList;
    if (!_video->getAllVideos(videoList))
    {
        resp.status = 500;
        resp.set_content(R"({"status":"error","message":"获取视频列表失败"})", "application/json");
        LOG_ERROR() << "获取视频列表失败";
        return;
    }

    Json::Value responseJson;
    responseJson["success"] = true;
    Json::Value videosJson(Json::arrayValue);

    for (const auto &video : videoList)
    {
        Json::Value videoJson;
        videoJson["video_id"] = video.video_id;
        videoJson["title"] = video.title;
        videoJson["description"] = video.description;
        videoJson["url"] = video.url;
        videoJson["thumbnail_url"] = video.thumbnail_url;
        videoJson["category"] = video.category;
        videoJson["tags"] = video.tags;

        videosJson.append(videoJson);
    }

    responseJson["videos"] = videosJson;

    // 使用 Json::StreamWriterBuilder 生成无格式化的 JSON 字符串
    Json::StreamWriterBuilder writer;
    writer["indentation"] = ""; // 取消缩进
    std::string responseBody = Json::writeString(writer, responseJson);

    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseBody, "application/json");
}

void ServerWrapper::handleCheckLoginStatus(const httplib::Request &req, httplib::Response &resp)
{
    auto cookies = req.get_header_value("Cookie");
    std::string session_id = StringUtil::extract_session_id(cookies);
    std::string username = session_store[session_id];

    if (username.empty())
    {
        LOG_DEBUG() << "handleCheckLoginStatus: 用户未登录";
        resp.status = 401;
        resp.set_header("Content-Type", "application/json");
        resp.set_content("{\"status\":\"error\",\"message\":\"未登录\"}", "application/json");
        return;
    }
    Json::Value responseJson;
    responseJson["status"] = "success";
    responseJson["isLoggedIn"] = true;

    resp.status = 200;
    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}   

void ServerWrapper::handleAddComment(const httplib::Request &req, httplib::Response &resp)
{
    // 获取 Cookie 和 session_id
    std::string cookies = req.get_header_value("Cookie");
    std::string session_id = StringUtil::extract_session_id(cookies);
    std::string username = session_store[session_id];
    int user_id = user.getUserId(username);
    LOG_DEBUG() << "handleAddComment: " << username << " " << user_id << " " << session_id;

    // 检查用户是否已登录
    if (username.empty())
    {
        LOG_ERROR() << "未登录用户无法评论";
        Json::Value responseJson;
        responseJson["success"] = false;
        responseJson["message"] = "未登录";
        resp.status = 401;
        resp.set_header("Content-Type", "application/json");
        resp.set_content(responseJson.toStyledString(), "application/json");
        return;
    }

    // 检查并获取必要参数
    if (!req.has_param("articleId") || !req.has_param("content"))
    {
        LOG_ERROR() << "缺少字段: articleId 或 content";
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"缺少字段: articleId 或 content"})", "application/json");
        return;
    }

    // 获取数据并验证
    int articleId;
    try
    {
        articleId = std::stoi(req.get_param_value("articleId"));
    }
    catch (const std::invalid_argument &e)
    {
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"articleId 必须是一个有效的整数"})", "application/json");
        LOG_ERROR() << "无效的 articleId: " << e.what();
        return;
    }
    catch (const std::out_of_range &e)
    {
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"articleId 超出范围"})", "application/json");
        LOG_ERROR() << "articleId 超出范围: " << e.what();
        return;
    }

    std::string content = req.get_param_value("content");
    // LOG_DEBUG() << "content: " << content << " articleId: " << articleId;

    LOG_DEBUG() << " before add comment";
    // 添加评论
    Json::Value responseJson;
    if (_comment->addComment(user_id, articleId, content, username))
    {
        _article->addCommentCount(articleId);
        // LOG_DEBUG() << "Comment added successfully for article " << articleId;
        responseJson["success"] = true;
        responseJson["message"] = "评论成功";
        resp.status = 200;
    }
    else
    {
        LOG_ERROR() << "Failed to add comment for article " << articleId;
        responseJson["success"] = false;
        responseJson["message"] = "添加评论失败";
        resp.status = 500;
    }

    // 设置响应内容
    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleLikeArticle(const httplib::Request &req, httplib::Response &resp)
{
    // 从请求体中解析 JSON 数据，提取 isLiked
    Json::Value reqJson;
    Json::Reader reader;
    if (!reader.parse(req.body, reqJson) || !reqJson.isMember("isLiked"))
    {
        LOG_DEBUG() << "handleLikeArticle: 请求体解析失败或缺少 isLiked 字段";
        resp.status = 400;
        resp.set_header("Content-Type", "application/json");
        resp.set_content("{\"status\":\"error\",\"message\":\"请求参数错误\"}", "application/json");
        return;
    }

    bool isLiked = reqJson["isLiked"].asBool();
    int articleId = std::stoi(req.get_param_value("id"));

    // 执行点赞或取消点赞的逻辑
    if (isLiked)
    {
        // 点赞
        _article->increaseLikeCount(articleId);
    }
    else
    {
        // 取消点赞
        _article->decreaseLikeCount(articleId);
    }

    // 获取更新后的点赞数
    int newLikeCount = _article->getLikeCount(articleId);

    // 返回 JSON 响应
    Json::Value responseJson;
    responseJson["status"] = "success";
    responseJson["new_like_count"] = newLikeCount;

    resp.status = 200;
    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleIncreaseViewCount(const httplib::Request &req, httplib::Response &resp)
{
    int articleId = std::stoi(req.get_param_value("id"));

    if (_article->increaseViewCount(articleId))
    {
        resp.status = 200;
        resp.set_header("Content-Type", "application/json");
        resp.set_content("{\"status\":\"success\"}", "application/json");
    }
    else
    {
        LOG_ERROR() << "增加浏览量失败";
        resp.status = 500;
        resp.set_header("Content-Type", "application/json");
        resp.set_content("{\"status\":\"error\",\"message\":\"增加浏览量失败\"}", "application/json");
    }
}

void ServerWrapper::handleGetComments(const httplib::Request &req, httplib::Response &resp)
{
    // 检查是否存在 articleId 参数
    if (!req.has_param("articleId"))
    {
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"缺少字段: articleId"})", "application/json");
        LOG_ERROR() << "缺少字段: articleId";
        return;
    }

    // 获取 articleId 并验证
    int articleId;
    try
    {
        articleId = std::stoi(req.get_param_value("articleId"));
    }
    catch (const std::invalid_argument &e)
    {
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"articleId 必须是一个有效的整数"})", "application/json");
        LOG_ERROR() << "无效的 articleId: " << e.what();
        return;
    }
    catch (const std::out_of_range &e)
    {
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"articleId 超出范围"})", "application/json");
        LOG_ERROR() << "articleId 超出范围: " << e.what();
        return;
    }

    // 获取评论列表
    std::vector<Comment> commentList;
    if (!_comment->getAllCommentsByArticleId(std::to_string(articleId), commentList))
    {
        resp.status = 500;
        resp.set_content(R"({"status":"error","message":"获取评论失败"})", "application/json");
        LOG_ERROR() << "获取评论失败";
        return;
    }

    // 构造 JSON 响应
    Json::Value responseJson;
    responseJson["success"] = true;
    Json::Value commentsJson(Json::arrayValue);

    for (const auto &comment : commentList)
    {
        Json::Value commentJson;
        commentJson["comment_id"] = comment.comment_id;
        commentJson["user_id"] = comment.user_id;
        commentJson["article_id"] = comment.article_id;
        commentJson["content"] = comment.content;
        commentJson["timestamp"] = comment.comment_time;

        std::string cookies = req.get_header_value("Cookie");
        std::string session_id = StringUtil::extract_session_id(cookies);
        std::string username = session_store[session_id];
        commentJson["username"] = username;
        std::string avatarUrl;
        user.getAvatarByUsername(username, avatarUrl);
        // LOG_DEBUG() << "avatarUrl: " << avatarUrl;
        commentJson["avatar"] = avatarUrl;

        commentsJson.append(commentJson);
    }

    // LOG_DEBUG() << "content: " << commentsJson;

    responseJson["comments"] = commentsJson;

    // 设置响应内容
    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleGetPosts(const httplib::Request &req, httplib::Response &resp)
{
    std::string category;
    if (req.has_param("category"))
    {
        category = req.get_param_value("category");
    }

    std::vector<Post> postList;
    if (!_post->getAllPosts(postList))
    {
        resp.status = 500;
        resp.set_content(R"({"status":"error","message":"获取文章失败"})", "application/json");
        LOG_ERROR() << "获取文章失败";
        return;
    }

    Json::Value responseJson;
    responseJson["success"] = true;
    Json::Value postsJson(Json::arrayValue);

    for (const auto &post : postList)
    {
        Json::Value postJson;
        postJson["post_id"] = post.post_id;
        postJson["user_id"] = post.user_id;
        postJson["content"] = post.content;
        postJson["date"] = post.date;
        postJson["view_count"] = post.view_count;
        postJson["like_count"] = post.like_count;
        postJson["comment_count"] = post.comment_count;
        postJson["category"] = post.category;
        postJson["tags"] = post.tags;
        postJson["image_url"] = post.image_url;

        std::string username = user.getNameById(post.user_id);
        postJson["username"] = username;

        std::string avatarUrl;
        user.getAvatarByUsername(username, avatarUrl);
        postJson["avatar"] = avatarUrl;

        postsJson.append(postJson);
    }

    responseJson["posts"] = postsJson;
    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}

void ServerWrapper::handleAddPost(const httplib::Request &req, httplib::Response &resp)
{
    int user_id = getUserId(req);

    if (user_id < 0)
    {
        LOG_ERROR() << "未登录用户无法发布文章";
        Json::Value responseJson;
        responseJson["success"] = false;
        responseJson["message"] = "未登录";
        resp.status = 401;
        resp.set_header("Content-Type", "application/json");
        resp.set_content(responseJson.toStyledString(), "application/json");
        return;
    }

    if (!req.has_file("content") || !req.has_file("category") || !req.has_file("tags"))
    {
        LOG_ERROR() << "缺少字段: content, category 或 tags";
        resp.status = 400;
        resp.set_content(R"({"status":"error","message":"缺少字段: content, category 或 tags"})", "application/json");
        return;
    }

    std::string content = req.get_file_value("content").content;
    std::string category = req.get_file_value("category").content;
    std::string tags = req.get_file_value("tags").content;

    // 如果有图片文件，保存图片
    std::string imagePath, savePath;
    if (req.has_file("image"))
    {
        auto imageFile = req.get_file_value("image");
        imagePath = "../oj_server/wwwRoot/resource/image/posts/" + imageFile.filename;
        savePath = "/resource/image/posts/" + imageFile.filename;
        if (!FileUtil::SetContent(imagePath, imageFile.content))
        {
            LOG_ERROR() << "Failed to save image: " << imagePath;
            resp.status = 500;
            resp.set_content(R"({"status":"error","message":"图片保存失败"})", "application/json");
            return;
        }
    }

    // 添加帖子
    Json::Value responseJson;

    if (_post->addPost(user_id, content, category, tags, savePath))
    {
        responseJson["success"] = true;
        responseJson["message"] = "文章发布成功";
        resp.status = 200;
    }
    else
    {
        LOG_ERROR() << "Failed to add post";
        responseJson["success"] = false;
        responseJson["message"] = "添加文章失败";
        resp.status = 500;
    }

    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");

}

void ServerWrapper::handleDeleteArticle(const httplib::Request &req, httplib::Response &resp)
{
    // 获取文章 ID 参数
    std::string tmp = req.get_param_value("id");
    int articleId = std::stoi(tmp);
    LOG_DEBUG() << "Deleting article, ID: " << articleId;

    Json::Value responseJson;
    // 尝试删除文章
    if (!_article->DeleteArticle(articleId))
    {
        LOG_ERROR() << "Failed to delete article, ID: " << articleId;
        responseJson["status"] = "error";
        responseJson["message"] = "删除文章失败";
        resp.status = 500;
    }
    else
    {
        LOG_INFO() << "Article successfully deleted, ID: " << articleId;
        responseJson["status"] = "success";
        responseJson["message"] = "文章已成功删除";
        resp.status = 200;
    }

    // 设置响应头和内容
    resp.set_header("Content-Type", "application/json");
    resp.set_content(responseJson.toStyledString(), "application/json");
}
